<template>
  <!-- 页面-应用管理-编辑 -->
  <div style="padding: 10px" class="AppEdit-page">
    <Form :model="modelForm" ref="editForm" :rules="rule" :label-width="80">
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item prop="clientId" :label="$t('module.appManage.appCode')">
            <Input
              :placeholder="$t('module.appManage.enterclientId')"
              v-model.trim="modelForm.clientId"
              :disabled="readOnly || !!appInfo.id"
            />
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="appName" :label="$t('module.appManage.appName')">
            <Input
              :placeholder="$t('module.appManage.enterappName')"
              v-model.trim="modelForm.appName"
              
              :disabled="readOnly"
            />
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">

        <Col span="12">
          <Form-item prop="tenantName" :label="$t('module.appManage.tenant')">
            <Input v-model="modelForm.tenantName" disabled  />
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="modelForm.enabled" size="small">
              <Radio :label="1" :disabled="readOnly">
                <span>{{ $t("common.enable") }}</span>
              </Radio>
              <Radio :label="0" :disabled="readOnly">
                <span>{{ $t("common.disable") }}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="18">
          <Form-item prop="clientSecretPlaintext" :label="$t('module.appManage.clientSecretPlaintext')">
            <Input v-model="modelForm.clientSecretPlaintext" disabled placeholder  :maxlength="50" />
          </Form-item>
        </Col>
        <Col span="6">
          <Form-item :labelWidth="0">
            <RPButton
              optType="reset"
              @click.native="getClientSecret"
              :text="$t('module.appManage.generateclientSecret')"
              style="borderradius: 0; width: 100%"
              :disabled="readOnly"
            />
          </Form-item>
        </Col>
      </Row>
    </Form>
  </div>
</template>
<script>
import { getUUID } from "@/tools/util.js";
import locales from "./locales.js";
import {
  getAppById,
  applicationAdd,
  applicationUpdate,
  getApplicationByCliendId
} from "@/api/applicationApi.js";
import valueSetAPI from "@/api/valueSetAPI.js";
import { getUserCenterList } from "@/api/userCenterApi.js";
import { CoreModuleName } from "@/const";
import tenantAPI from "@/api/tenantApi.js";

export default {
  name: "appedite",
  mixins: [locales],
  props: {
    appInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    tenantName: {
      type: String,
      default() {
        return "";
      }
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    const { userInfo } = $store.state[CoreModuleName];
    const validateclientId = (rule, value, callback) => {
      if (value === '') {
          callback(new Error(this.$t("module.appManage.enterclientId")));
      } else if (/^[a-zA-Z0-9|_|\-|\.]+$/.test(value) && value.length <= 32) {
        if (this.appInfo.id) {
          callback()
        } else {
          if (this.clientIdFlag == 0) {
            getApplicationByCliendId([value]).then(res => {
              if (res.data.length != 0) {
                callback(new Error('该编码已存在或已被内部使用'))
                this.clientIdFlag = 1
              } else {
                this.clientIdFlag = 2
                callback()
              }
            })
          } else if (this.clientIdFlag == 1) {
            callback(new Error('该编码已存在或已被内部使用'))
          } else {
            callback()
          }
        }
      } else {
        callback()
      }
    }
    return {
      currTenantCode: userInfo.tenantCode || "", //租户编码
      actions: [],
      isReadyOnly: false,
      // scopes: {},
      isOpen: false,
      // 判断clientId 是否已经经过校验，避免多次点击保存按钮，重复进行接口调用0表示clientId已修改且没有经过校验，1，表示该值已经校验过，且数据库有重复值，2表示校验通过
      clientIdFlag: 0,
      modelForm: {
        clientId: null,
        appName: null,
        tenantName: null,
        clientSecretPlaintext: null,
        enabled: 1,
      },
      rule: {
        clientId: [
          {
            required: true,
            trigger: "blur",
            validator: validateclientId.bind(this)
          },
          {
            type: 'string',
            max: 32,
            message: this.$t("common.warning.lengMaxFormat", ['32'])
          }, 
          {
            type: 'string',
            pattern: /^[a-zA-Z0-9|_|\-|\.]+$/,
            message: this.$t("common.warning.codeFormat")
          }
        ],
        appName: [
          {
            required: true,
            message: this.$t("module.appManage.enterappName"),
            trigger: "blur"
          },
          {
            type: 'string',
            max: 64,
            message: this.$t("common.warning.lengMaxFormat", ['64'])
          },
          {
            type: 'string',
            pattern: /[\u4E00-\u9FA5]|[A-Z]|[a-z]|[0-9]/,
            message: this.$t("common.warning.nameFormat")
          }
        ],
        clientSecretPlaintext: [
          {
            required: true,
            message: this.$t("module.appManage.enterclientSecret"),
            trigger: "blur"
          }
        ],
        tenantName: [{ required: true, trigger: "blur" }],
      }
    };
  },
  created() {
    if (this.readOnly) {
      this.$emit("SetTitle", this.$t("common.detail"));
    } else if (this.appInfo.id) {
      this.$emit("SetTitle", this.$t("module.appManage.editApp"));
    } else {
      let uuid = getUUID().replace(new RegExp("-", "g"), "");
      this.modelForm.clientId = uuid
      this.$emit("SetTitle", this.$t("module.appManage.createApp"));
    }
    this.$emit("SetPageMinHeight", 200);
    // 调整宽度
    this.$emit("SetPageWidth", 830);
    if (!this.readOnly) {
      this.actions.push({
        text: this.$t("common.save"),
        theme: "primary",
        handle: () => {
          this.save();
        },
        loading: false
      });
    }
    this.actions.push({
      text: this.$t("common.close"),
      handle: () => {
        this.$emit("Close");
      }
    });
    this.$emit("SetPageActions", this.actions);
    this.initData();
  },
  methods: {
    getClientSecret() {
      let temp = getUUID().replace(new RegExp("-", "g"), "");
      this.modelForm.clientSecretPlaintext = temp;
    },
    async initData() {
      // if()
      // this.searchScope();
      //获取产品类型
      const result = await Promise.all([valueSetAPI.getValueSetByCode("LOGIN_MODE"), getUserCenterList()]);
      //   结构赋值
      const [dicArrLogin, { data: userTemp }] = result;

      if (!!this.appInfo.id) {
        this.isReadyOnly = true;
        this.getDataById();
      }
      //新增时
      if (!this.appInfo.id) {
        this.modelForm.tenantName = this.tenantName;
      }
    },
    getDataById() {
      getAppById(this.appInfo.id)
        .then(response => {
          Object.assign(this.modelForm, response.data);
          const res = response.data;
          this.initTenant(res.tenantCode); //获取租户编码对应的租户名称
        })
        .catch(error => {
          this.$message.error({
            content: error.message,
            duration: 3
          });
        });
    },
    // 初始化所属租户,获取租户编码对应的租户名称
    initTenant(tenantCode) {
      tenantAPI.queryAllTenantList().then(data => {
        for (const tenant of data) {
          if (tenantCode == tenant.tenantCode) {
            this.modelForm.tenantName = tenant.tenantName;
          }
        }
      });
    },
    save() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          if (!this.appInfo.id) {
            applicationAdd(this.modelForm)
            .then(response => {
              this.actions[0].loading = false;
              const content = this.appInfo.id
                ? this.$t("module.valueSet.updateSuccess")
                : this.$t("module.valueSet.createSuccess");
              this.$message.success({
                content: content,
                duration: 3
              });
              this.$emit("Close", true);
            })
            .catch(err => {
              this.actions[0].loading = false;
            });
          } else {
            applicationUpdate(this.modelForm)
            .then(response => {
              this.actions[0].loading = false;
              const content = this.appInfo.id
                ? this.$t("module.valueSet.updateSuccess")
                : this.$t("module.valueSet.createSuccess");
              this.$message.success({
                content: content,
                duration: 3
              });
              this.$emit("Close", true);
            })
            .catch(err => {
              this.actions[0].loading = false;
            });
          }
         
        } else {
          this.$message.error({
            content: this.$t("module.valueSet.formValidateFailed"),
            duration: 3
          });
          return 0;
        }
      });
    }
  },
  watch: {
    'modelForm.clientId': {
      handler() {
        this.clientIdFlag = 0
      }
    }
  }
};
</script>
<style lang="less">
.AppEdit-page {
  .accessTokenValidity,
  .refreshTokenValidity {
    .ivu-input-wrapper {
      width: calc(~"100% - 14px") !important;
    }
  }
}
</style>
